/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hvtt.web.controller;

import com.hvtt.web.connection.Command;
import com.hvtt.web.connection.WEBConnection;
import com.hvtt.web.connection.WEBParamCollection;
import com.hvtt.web.models.Sys_UserModel;
import com.hvtt.web.models.Sys_nguoidung;
import com.hvtt.web.utilities.Utilities;
import java.io.IOException;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Administrator
 */
@ManagedBean
@SessionScoped
public class Sys_NguoiDungController implements Serializable {

    private WEBConnection DAL = WEBConnection.getInstance();
    private Sys_nguoidung item = new Sys_nguoidung();
    private String nhapLaiMatkhau = "";
    private boolean  blnIsSellClick=false;

    public String getNhapLaiMatKhau() {
        return nhapLaiMatkhau;
    }

    public void setNhapLaiMatKhau(String nhapLaiMatKhau) {
        this.nhapLaiMatkhau = nhapLaiMatKhau;
    }

    public Sys_nguoidung getItem() {
        return item;
    }

    public void setItem(Sys_nguoidung item) {
        this.item = item;
    }

    private boolean isValidEmailAddress(String email) {
        boolean result = true;
        try {
            InternetAddress emailAddr = new InternetAddress(email);
            emailAddr.validate();
        } catch (AddressException ex) {
            result = false;
        }
        return result;
    }

    private String validateFields() throws SQLException {
        String str = "";
        if (StringUtils.isBlank(this.getItem().getMa())) {
            str = "  + " + Utilities.getLanguages("UserName") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (this.getItem().getLoai() == 0 && (StringUtils.isBlank(this.getItem().getLoaiXeBan()) || "null".equals(this.getItem().getLoaiXeBan().trim()))) {
            str = "  + " + Utilities.getLanguages("HangSX") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (StringUtils.isBlank(this.getItem().getEmail())) {
            str += "  + " + Utilities.getLanguages("Email") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (!isValidEmailAddress(this.getItem().getEmail())) {
            str += "  + " + Utilities.getLanguages("Email") + ": " + Utilities.getLanguages("SaiCauTrucEmail") + "<br/>";
        }
        WEBParamCollection Params = new WEBParamCollection();
        Params.add(this.getItem().getEmail());
        Params.add(this.getItem().getMa());
        ResultSet rs = DAL.executeQuery1("{call PG_Load_Sys_NguoiDung_DangKy_Check_Email(?,?)}", Command.sqlStoredProcedure, Params);
        if (rs != null) {
            if (rs.next()) {
                int iCheck = rs.getInt(1);
                if (iCheck == -2) {
                    str += "  + " + Utilities.getLanguages("UserName") + ": " + Utilities.getLanguages("ReadyExists") + "<br/>";
                } else if (iCheck == -1) {
                    str += "  + " + Utilities.getLanguages("Email") + ": " + Utilities.getLanguages("ReadyExists") + "<br/>";
                }

            }
        }

        if (StringUtils.isBlank(this.getItem().getMatKhau())) {
            str += "  + " + Utilities.getLanguages("MatKhau") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (this.getItem().getMatKhau().length() < 6) {
            str += "  + " + Utilities.getLanguages("MatKhau") + ": " + Utilities.getLanguages("MinLength") + " 6 " + Utilities.getLanguages("Character") + "<br/>";
        }
        if (this.getItem().getMatKhau().trim() == null ? this.getNhapLaiMatKhau().trim() != null : !this.getItem().getMatKhau().trim().equals(this.getNhapLaiMatKhau().trim())) {
            str += "  + " + Utilities.getLanguages("MatKhauAndNhapLaiMatKhau") + "<br/>";
        }
        if (this.getItem().getLoai() == 0 && "".equals(this.getItem().getLoaiXeBan().trim())) {
            str += "  + " + Utilities.getLanguages("HangSX") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (StringUtils.isBlank(this.getItem().getHo())) {
            str += "  + " + Utilities.getLanguages("Ho") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (StringUtils.isBlank(this.getItem().getTen())) {
            str += "  + " + Utilities.getLanguages("Ten") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if ("".equals(str.trim())) {
            return "";
        }
        return "<b style='color:black;'>" + Utilities.getLanguages("AdMsg0010") + ":</b> <br/>" + "<b style='color:red;'>" + str + "</b>";
    }
    private String validateFields_ThongTinCaNhan() throws SQLException {
        String str = "";
        if (StringUtils.isBlank(this.getItem().getMa())) {
            str = "  + " + Utilities.getLanguages("UserName") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (this.getItem().getLoai() == 0 && (StringUtils.isBlank(this.getItem().getLoaiXeBan()) || "null".equals(this.getItem().getLoaiXeBan().trim()))) {
            str = "  + " + Utilities.getLanguages("HangSX") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (StringUtils.isBlank(this.getItem().getEmail())) {
            str += "  + " + Utilities.getLanguages("Email") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (!isValidEmailAddress(this.getItem().getEmail())) {
            str += "  + " + Utilities.getLanguages("Email") + ": " + Utilities.getLanguages("SaiCauTrucEmail") + "<br/>";
        }
        
        if (!StringUtils.isBlank(this.getItem().getMatKhau())) {
             if (this.getItem().getMatKhau().length() < 6) {
                    str += "  + " + Utilities.getLanguages("MatKhau") + ": " + Utilities.getLanguages("MinLength") + " 6 " + Utilities.getLanguages("Character") + "<br/>";
                }
                if (this.getItem().getMatKhau().trim() == null ? this.getNhapLaiMatKhau().trim() != null : !this.getItem().getMatKhau().trim().equals(this.getNhapLaiMatKhau().trim())) {
                    str += "  + " + Utilities.getLanguages("MatKhauAndNhapLaiMatKhau") + "<br/>";
                }
        }
       
//        if (this.getItem().getLoai() == 0 && "".equals(this.getItem().getLoaiXeBan().trim())) {
//            str += "  + " + Utilities.getLanguages("HangSX") + ": " + Utilities.getLanguages("Require") + "<br/>";
//        }
        if (StringUtils.isBlank(this.getItem().getHo())) {
            str += "  + " + Utilities.getLanguages("Ho") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if (StringUtils.isBlank(this.getItem().getTen())) {
            str += "  + " + Utilities.getLanguages("Ten") + ": " + Utilities.getLanguages("Require") + "<br/>";
        }
        if ("".equals(str.trim())) {
            return "";
        }
        return "<b style='color:black;'>" + Utilities.getLanguages("AdMsg0010") + ":</b> <br/>" + "<b style='color:red;'>" + str + "</b>";
    }
    public void DangKy(ActionEvent event) throws IOException, SQLException {

        this.getItem().setGioiTinh(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("GioiTinh")));
//        this.getItem().setLoai(Integer.valueOf(
//                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("Loai")));
        this.getItem().setLoaiXeBan(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangSX")));
        this.getItem().setQuocGiaID(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("QuocGiaID")));
        this.getItem().setTinhID(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TinhID")));

        String result = this.validateFields();
        if (!result.isEmpty()) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", result);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("update=\"growl\"");
            return;
        }


        try {

            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();


            String urlActive = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() != 80 ? ":" : "") + (request.getServerPort() != 80 ? String.valueOf(request.getServerPort()) : "") + "/active.html?usrid=" + this.getItem().getMa();
            //String strNoiDung=String.format(Utilities.getLanguages("NoiDungEmailDangKyThanhCong"), urlActive,Utilities.getLanguages("ActiveAccount"));
            //String strNoiDung = Utilities.getLanguages("NoiDungEmailDangKyThanhCong") + "<br/><a href='" + request.getScheme() + "://" + request.getServerName() + (request.getServerPort() != 80 ? ":" : "") + (request.getServerPort() != 80 ? String.valueOf(request.getServerPort()) : "") + "/active.html?usrid=" + this.getItem().getMa() + "'>" + Utilities.getLanguages("ActiveAccount") + "</a>";

            String mailContent = "<table width=\"100%\">\n"
                    + "                    <tbody>\n"
                    + "		<tr>\n"
                    + "			<td style=\"background-color:#e9e9e9;padding:20px\">\n"
                    + "				<table cellspacing=\"0\" cellpadding=\"0\" align=\"center\" style=\"border-collapse:collapse;width:600px;max-width:640px;font-family:arial,sans-serif;margin-bottom:50px\">\n"
                    + "					<tbody>\n"
                    + "						<tr>\n"
                    + "							<td style=\"padding:0\">\n"
                    + "								<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" style=\"border-collapse:collapse;background:white\">\n"
                    + "									<tbody>\n"
                    + "										<tr>\n"
                    + "											<td style=\"background:#00b9f2;height:69px;padding:10px 30px\">\n"
                    + "												<table cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse;width:100%\">\n"
                    + "													<tbody>\n"
                    + "														<tr>\n"
                    + "															<td style=\"height:30px\">\n"
                    + "																<p style=\"margin:0;font-family:Arial,sans-serif;font-size:24px;color:#fff;font-weight:bold\">\n"
                    + "																	Hoàn Tất Đăng Ký</p>\n"
                    + "															</td>\n"
                    + "															<td align=\"right\">\n"
                    + "																<a target=\"_blank\" style=\"border:none;outline:none\" href=\"http://autoko.co\"> \n"
                    + "                                                                                                                                    <img width=\"118\" height=\"100\" alt=\"autoko.co\" src=\"http://autoko.co/resourcesApp/img/sagoauto/AUTOKO.png\" style=\"border:none;outline:none\"/>\n"
                    + "                                                                                                                                </a></td>\n"
                    + "														</tr>\n"
                    + "													</tbody>\n"
                    + "												</table>\n"
                    + "											</td>\n"
                    + "										</tr>\n"
                    + "										<tr>\n"
                    + "											<td style=\"padding:30px\">\n"
                    + "												<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse\">\n"
                    + "													<tbody>\n"
                    + "														<tr>\n"
                    + "															<td style=\"font-family:Arial,sans-serif;font-size:14px;line-height:24px;color:#555\">\n"
                    + "																<p style=\"margin:0\">\n"
                    + "																	Chào <strong>" + this.item.getTen() + "</strong>,</p>\n"
                    + "																<p style=\"margin:0;color: #333333;\">\n"
                    + "                                                                                                                                    Tài khoản của bạn đã được đăng ký thành công trên <a href=\"http://www.autoko.co\">www.autoko.co. </a>\n"
                    + "                                                                                                                                    Để đăng nhập vào website của chúng tôi bạn click <b>Active</b> để hoàn tất việc đăng ký.\n"
                    + "                                                                                                                                </p>\n"
                    + "															</td>\n"
                    + "														</tr>\n"
                    + "														<tr><td></td></tr>\n"
                    + "                                                                                                                									\n"
                    + "														<tr>\n"
                    + "															<td align=\"center\">\n"
                    + "																<div style=\"margin:60px 0 5px;clear:both\">\n"
                    + "																	<strong><a style=\"font-family:Arial,sans-serif;font-size:18px;text-decoration:none;color:#fff;padding:15px 30px;background:#f7941d\" href=\"" + urlActive + "\"> " + Utilities.getLanguages("ActiveAccount") + " &gt;&gt;</a></strong></div>\n"
                    + "															</td>\n"
                    + "														</tr>\n"
                    + "													</tbody>\n"
                    + "												</table>\n"
                    + "											</td>\n"
                    + "										</tr>\n"
                    + "										<tr>\n"
                    + "											<td style=\"font-size:11px;font-family:Arial,sans-serif;color:#999;text-align:center;padding-bottom:30px\">\n"
                    + "                                                                                            Copyright © <a href=\"http://www.autoko.co\">autoko.co</a></td>\n"
                    + "										</tr>\n"
                    + "									</tbody>\n"
                    + "								</table>\n"
                    + "							</td>\n"
                    + "						</tr>\n"
                    + "					</tbody>\n"
                    + "				</table>\n"
                    + "			</td>\n"
                    + "		</tr>\n"
                    + "	</tbody>\n"
                    + "</table>";
            String mailContentEN = "<table width=\"100%\">\n"
                    + "                    <tbody>\n"
                    + "		<tr>\n"
                    + "			<td style=\"background-color:#e9e9e9;padding:20px\">\n"
                    + "				<table cellspacing=\"0\" cellpadding=\"0\" align=\"center\" style=\"border-collapse:collapse;width:600px;max-width:640px;font-family:arial,sans-serif;margin-bottom:50px\">\n"
                    + "					<tbody>\n"
                    + "						<tr>\n"
                    + "							<td style=\"padding:0\">\n"
                    + "								<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" style=\"border-collapse:collapse;background:white\">\n"
                    + "									<tbody>\n"
                    + "										<tr>\n"
                    + "											<td style=\"background:#00b9f2;height:69px;padding:10px 30px\">\n"
                    + "												<table cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse;width:100%\">\n"
                    + "													<tbody>\n"
                    + "														<tr>\n"
                    + "															<td style=\"height:30px\">\n"
                    + "																<p style=\"margin:0;font-family:Arial,sans-serif;font-size:24px;color:#fff;font-weight:bold\">\n"
                    + "																	Completion Register</p>\n"
                    + "															</td>\n"
                    + "															<td align=\"right\">\n"
                    + "																<a target=\"_blank\" style=\"border:none;outline:none\" href=\"http://www.autoko.co\"> \n"
                    + "                                                                                                                                    <img width=\"118\" height=\"100\" alt=\"autoko.co\" src=\"http://autoko.co/resourcesApp/img/sagoauto/AUTOKO.png\" style=\"border:none;outline:none\"/>\n"
                    + "                                                                                                                                </a></td>\n"
                    + "														</tr>\n"
                    + "													</tbody>\n"
                    + "												</table>\n"
                    + "											</td>\n"
                    + "										</tr>\n"
                    + "										<tr>\n"
                    + "											<td style=\"padding:30px\">\n"
                    + "												<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse\">\n"
                    + "													<tbody>\n"
                    + "														<tr>\n"
                    + "															<td style=\"font-family:Arial,sans-serif;font-size:14px;line-height:24px;color:#555\">\n"
                    + "																<p style=\"margin:0\">\n"
                    + "																	Hi <strong>" + this.item.getTen() + "</strong>,</p>\n"
                    + "																<p style=\"margin:0;color: #333333;\">\n"
                    + "                                                                                                                                    Your account has been successfully registered on <a href=\"http://www.autoko.co\">www.autoko.co. </a>\n"
                    + "                                                                                                                                    To log into our website you click <b>Active</b> to complete the registration.\n"
                    + "                                                                                                                                </p>\n"
                    + "															</td>\n"
                    + "														</tr>\n"
                    + "														<tr><td></td></tr>\n"
                    + "                                                                                                                									\n"
                    + "														<tr>\n"
                    + "															<td align=\"center\">\n"
                    + "																<div style=\"margin:60px 0 5px;clear:both\">\n"
                    + "																	<strong><a style=\"font-family:Arial,sans-serif;font-size:18px;text-decoration:none;color:#fff;padding:15px 30px;background:#f7941d\" href=\"" + urlActive + "\"> " + Utilities.getLanguages("ActiveAccount") + " &gt;&gt;</a></strong></div>\n"
                    + "															</td>\n"
                    + "														</tr>\n"
                    + "													</tbody>\n"
                    + "												</table>\n"
                    + "											</td>\n"
                    + "										</tr>\n"
                    + "										<tr>\n"
                    + "											<td style=\"font-size:11px;font-family:Arial,sans-serif;color:#999;text-align:center;padding-bottom:30px\">\n"
                    + "                                                                                            Copyright © <a href=\"http://www.autoko.co\">autoko.co</a></td>\n"
                    + "										</tr>\n"
                    + "									</tbody>\n"
                    + "								</table>\n"
                    + "							</td>\n"
                    + "						</tr>\n"
                    + "					</tbody>\n"
                    + "				</table>\n"
                    + "			</td>\n"
                    + "		</tr>\n"
                    + "	</tbody>\n"
                    + "</table>";
            
            boolean bln = Utilities.sendMail(this.item.getEmail(), Utilities.getLanguages("TieuDeEmailDangKyThanhCong"), "VN".equals(Utilities.getCurrentLanguage())?mailContent:mailContentEN);


            WEBParamCollection Params = new WEBParamCollection();
            Params.add(this.item.getMa());
            Params.add(this.item.getMatKhau());
            Params.add(this.item.getHo());
            Params.add(this.item.getTen());
            Params.add(this.item.getGioiTinh());
            Params.add(this.item.getDiaChi());
            Params.add(this.item.getDienThoai());
            Params.add(this.item.getDienThoaiNha());
            Params.add(this.item.getEmail());
            Params.add(this.item.getQuocGiaID());
            Params.add(this.item.getNgonNguID());
            Params.add(this.item.getLoai());
            Params.add(this.item.getIP());
            Params.add(this.item.getCapChaCode());
            if (bln) {
                Params.add(0);
            } else {
                Params.add(-2);
            }
            Params.add("Inside");
            Params.add(this.item.getLoaiXeBan());
            Params.add(this.item.getTinhID());
            DAL.executeUpdate("{call Proc_Sys_NguoiDung_DangKy(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params);
            FacesContext.getCurrentInstance().getExternalContext().redirect("/registrySuccess.html");

        } catch (Exception ex) {
            throw ex;
        }
    }
    public void ThayDoiThongTinCaNhan_Click(ActionEvent event) throws IOException, SQLException {

        this.getItem().setGioiTinh(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("GioiTinh")));
//        this.getItem().setLoai(Integer.valueOf(
//                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("Loai")));
        this.getItem().setLoaiXeBan(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangSX")));
        this.getItem().setQuocGiaID(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("QuocGiaID")));
        this.getItem().setTinhID(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TinhID")));

        String result = this.validateFields_ThongTinCaNhan();
        if (!result.isEmpty()) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", result);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("update=\"growl\"");
            return;
        }


        try {

            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();


            
            WEBParamCollection Params = new WEBParamCollection();
            Params.add(this.item.getMa());
            Params.add(this.item.getMatKhau());
            Params.add(this.item.getHo());
            Params.add(this.item.getTen());
            Params.add(this.item.getGioiTinh());
            Params.add(this.item.getDiaChi());
            Params.add(this.item.getDienThoai());
            Params.add(this.item.getDienThoaiNha());
            Params.add(this.item.getEmail());
            Params.add(this.item.getQuocGiaID());
            Params.add(this.item.getTinhID());
            Params.add(this.item.getLoaiXeBan());
            DAL.executeUpdate("{call Proc_Sys_NguoiDung_CapNhat(?,?,?,?,?,?,?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params);
            FacesContext.getCurrentInstance().getExternalContext().redirect("/index.html");

        } catch (Exception ex) {
            throw ex;
        }
    }
    

    public void dangKyWithOpenId(ActionEvent event) {

        this.getItem().setLoai(Integer.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("Loai")));
        this.getItem().setLoaiXeBan(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangSX")));
        this.getItem().setQuocGiaID(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("QuocGiaID")));
        this.getItem().setTinhID(String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TinhID")));

        WEBParamCollection Params = new WEBParamCollection();
        Params.add(this.item.getMa());
        Params.add(null);
        Params.add(this.item.getHo());
        Params.add(this.item.getTen());
        Params.add(this.item.getGioiTinh());
        Params.add(this.item.getDiaChi());
        Params.add(this.item.getDienThoai());
        Params.add(this.item.getDienThoaiNha());
        Params.add(this.item.getEmail());
        Params.add(this.item.getQuocGiaID());
        Params.add(this.item.getNgonNguID());
        Params.add(this.item.getLoai());
        Params.add(this.item.getIP());
        Params.add(this.item.getCapChaCode());
        Params.add(1);
        Params.add(this.item.getOpenIdType());
        Params.add(this.item.getLoaiXeBan());
        Params.add(this.item.getTinhID());
        DAL.executeUpdate("{call Proc_Sys_NguoiDung_DangKy(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params);
        //Utilities.redirect("/registrySuccess.html");
        this.item.setNhomID("USERS");
        loginOpenId(this.item);
    }

    public String RandomPassword() {
        char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 9; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        return sb.toString().toUpperCase();
    }

    public void ForgetPassword(ActionEvent event) throws IOException, SQLException {


        String strEmail = String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("Email"));
        if ("".equals(strEmail.trim())) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", Utilities.getLanguages("Email") + ": " + Utilities.getLanguages("Require"));
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("update=\"growl\"");
            return;
        }
        try {
            WEBParamCollection Params1 = new WEBParamCollection();
            Params1.add(strEmail);
            List<Sys_nguoidung> lst = DAL.executeQuery("Select sys_nguoidung.Ma,sys_nguoidung.Ho,sys_nguoidung.Ten from sys_nguoidung where sys_nguoidung.Email=?", Command.sqlText, Params1, Sys_nguoidung.class);
            if (lst == null || lst.size() <= 0) {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", Utilities.getLanguages("EmailNotExists"));
                FacesContext.getCurrentInstance().addMessage(null, msg);
                RequestContext.getCurrentInstance().execute("update=\"growl\"");
                return;
            }

            String randomPass = RandomPassword();



            WEBParamCollection Params = new WEBParamCollection();
            Params.add(randomPass);
            Params.add(strEmail);

            DAL.executeUpdate("Update sys_nguoidung set sys_nguoidung.MatKhau=MD5(?) where sys_nguoidung.Email=?", Command.sqlStoredProcedure, Params);


            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String urlLogin = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() != 80 ? ":" : "") + (request.getServerPort() != 80 ? String.valueOf(request.getServerPort()) : "") + "/login.html";
            String mailContent = "<table width=\"100%\">\n"
                    + "                    <tbody>\n"
                    + "		<tr>\n"
                    + "			<td style=\"background-color:#e9e9e9;padding:20px\">\n"
                    + "				<table cellspacing=\"0\" cellpadding=\"0\" align=\"center\" style=\"border-collapse:collapse;width:600px;max-width:640px;font-family:arial,sans-serif;margin-bottom:50px\">\n"
                    + "					<tbody>\n"
                    + "						<tr>\n"
                    + "							<td style=\"padding:0\">\n"
                    + "								<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" style=\"border-collapse:collapse;background:white\">\n"
                    + "									<tbody>\n"
                    + "										<tr>\n"
                    + "											<td style=\"background:#00b9f2;height:69px;padding:10px 30px\">\n"
                    + "												<table cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse;width:100%\">\n"
                    + "													<tbody>\n"
                    + "														<tr>\n"
                    + "															<td style=\"height:30px\">\n"
                    + "																<p style=\"margin:0;font-family:Arial,sans-serif;font-size:24px;color:#fff;font-weight:bold\">\n"
                    + "																	Cập Nhật Mật Khẩu Thành Công</p>\n"
                    + "															</td>\n"
                    + "															<td align=\"right\">\n"
                    + "																<a target=\"_blank\" style=\"border:none;outline:none\" href=\"http://www.autoko.co\"> \n"
                    + "                                                                                                                                    <img width=\"118\" height=\"100\" alt=\"autoko.co\" src=\"http://autoko.co/resourcesApp/img/sagoauto/AUTOKO.png\" style=\"border:none;outline:none\"/>\n"
                    + "                                                                                                                                </a></td>\n"
                    + "														</tr>\n"
                    + "													</tbody>\n"
                    + "												</table>\n"
                    + "											</td>\n"
                    + "										</tr>\n"
                    + "										<tr>\n"
                    + "											<td style=\"padding:30px\">\n"
                    + "												<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse\">\n"
                    + "													<tbody>\n"
                    + "														<tr>\n"
                    + "															<td style=\"font-family:Arial,sans-serif;font-size:14px;line-height:24px;color:#555\">\n"
                    + "																<p style=\"margin:0\">\n"
                    + "																	Chào <strong>" + lst.get(0).getHo()+" "+lst.get(0).getTen() + "</strong>,</p>\n"
                    + "																<p style=\"margin:0;color: #333333;\">\n"
                    + "                                                                                                                                    Mật khẩu của bạn đã được reset thành công trên <a href=\"http://www.autoko.co\">www.autoko.co. </a>\n"
                    + "                                                                                                                                    Mật khẩu mới của bạn là : <b>" + randomPass + "</b>. Click link bên dưới để đăng nhập trở lại.\n"
                    + "                                                                                                                                </p>\n"
                    + "															</td>\n"
                    + "														</tr>\n"
                    + "														<tr><td></td></tr>\n"
                    + "                                                                                                                									\n"
                    + "														<tr>\n"
                    + "															<td align=\"center\">\n"
                    + "																<div style=\"margin:60px 0 5px;clear:both\">\n"
                    + "																	<strong><a style=\"font-family:Arial,sans-serif;font-size:18px;text-decoration:none;color:#fff;padding:15px 30px;background:#f7941d\" href=\"" + urlLogin + "\"> " + Utilities.getLanguages("DangNhap") + " &gt;&gt;</a></strong></div>\n"
                    + "															</td>\n"
                    + "														</tr>\n"
                    + "													</tbody>\n"
                    + "												</table>\n"
                    + "											</td>\n"
                    + "										</tr>\n"
                    + "										<tr>\n"
                    + "											<td style=\"font-size:11px;font-family:Arial,sans-serif;color:#999;text-align:center;padding-bottom:30px\">\n"
                    + "                                                                                            Copyright © <a href=\"http://www.autoko.co\">autoko.co</a></td>\n"
                    + "										</tr>\n"
                    + "									</tbody>\n"
                    + "								</table>\n"
                    + "							</td>\n"
                    + "						</tr>\n"
                    + "					</tbody>\n"
                    + "				</table>\n"
                    + "			</td>\n"
                    + "		</tr>\n"
                    + "	</tbody>\n"
                    + "</table>";
            
             String mailContentEN = "<table width=\"100%\">\n"
                    + "                    <tbody>\n"
                    + "		<tr>\n"
                    + "			<td style=\"background-color:#e9e9e9;padding:20px\">\n"
                    + "				<table cellspacing=\"0\" cellpadding=\"0\" align=\"center\" style=\"border-collapse:collapse;width:600px;max-width:640px;font-family:arial,sans-serif;margin-bottom:50px\">\n"
                    + "					<tbody>\n"
                    + "						<tr>\n"
                    + "							<td style=\"padding:0\">\n"
                    + "								<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" style=\"border-collapse:collapse;background:white\">\n"
                    + "									<tbody>\n"
                    + "										<tr>\n"
                    + "											<td style=\"background:#00b9f2;height:69px;padding:10px 30px\">\n"
                    + "												<table cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse;width:100%\">\n"
                    + "													<tbody>\n"
                    + "														<tr>\n"
                    + "															<td style=\"height:30px\">\n"
                    + "																<p style=\"margin:0;font-family:Arial,sans-serif;font-size:24px;color:#fff;font-weight:bold\">\n"
                    + "																	Update password success!</p>\n"
                    + "															</td>\n"
                    + "															<td align=\"right\">\n"
                    + "																<a target=\"_blank\" style=\"border:none;outline:none\" href=\"http://www.autoko.co\"> \n"
                    + "                                                                                                                                    <img width=\"118\" height=\"100\" alt=\"autoko.co\" src=\"http://autoko.co/resourcesApp/img/sagoauto/AUTOKO.png\" style=\"border:none;outline:none\"/>\n"
                    + "                                                                                                                                </a></td>\n"
                    + "														</tr>\n"
                    + "													</tbody>\n"
                    + "												</table>\n"
                    + "											</td>\n"
                    + "										</tr>\n"
                    + "										<tr>\n"
                    + "											<td style=\"padding:30px\">\n"
                    + "												<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse\">\n"
                    + "													<tbody>\n"
                    + "														<tr>\n"
                    + "															<td style=\"font-family:Arial,sans-serif;font-size:14px;line-height:24px;color:#555\">\n"
                    + "																<p style=\"margin:0\">\n"
                    + "																	Hi <strong>" + lst.get(0).getHo()+" "+lst.get(0).getTen() + "</strong>,</p>\n"
                    + "																<p style=\"margin:0;color: #333333;\">\n"
                    + "                                                                                                                                    The password was reseted <a href=\"http://www.autoko.co\">www.autoko.co. </a>\n"
                    + "                                                                                                                                    The new password : <b>" + randomPass + "</b>. Click link here.\n"
                    + "                                                                                                                                </p>\n"
                    + "															</td>\n"
                    + "														</tr>\n"
                    + "														<tr><td></td></tr>\n"
                    + "                                                                                                                									\n"
                    + "														<tr>\n"
                    + "															<td align=\"center\">\n"
                    + "																<div style=\"margin:60px 0 5px;clear:both\">\n"
                    + "																	<strong><a style=\"font-family:Arial,sans-serif;font-size:18px;text-decoration:none;color:#fff;padding:15px 30px;background:#f7941d\" href=\"" + urlLogin + "\"> " + Utilities.getLanguages("DangNhap") + " &gt;&gt;</a></strong></div>\n"
                    + "															</td>\n"
                    + "														</tr>\n"
                    + "													</tbody>\n"
                    + "												</table>\n"
                    + "											</td>\n"
                    + "										</tr>\n"
                    + "										<tr>\n"
                    + "											<td style=\"font-size:11px;font-family:Arial,sans-serif;color:#999;text-align:center;padding-bottom:30px\">\n"
                    + "                                                                                            Copyright © <a href=\"http://www.autoko.co\">autoko.co</a></td>\n"
                    + "										</tr>\n"
                    + "									</tbody>\n"
                    + "								</table>\n"
                    + "							</td>\n"
                    + "						</tr>\n"
                    + "					</tbody>\n"
                    + "				</table>\n"
                    + "			</td>\n"
                    + "		</tr>\n"
                    + "	</tbody>\n"
                    + "</table>";
//            String strNoiDung = Utilities.getLanguages("NoiDungForgetPassword") + "<br/><a href='" + request.getScheme() + "://" + request.getServerName() + (request.getServerPort() != 80 ? ":" : "") + (request.getServerPort() != 80 ? String.valueOf(request.getServerPort()) : "") + "'>" + request.getScheme() + "://" + request.getServerName() + (request.getServerPort() != 80 ? ":" : "") + (request.getServerPort() != 80 ? String.valueOf(request.getServerPort()) : "") + "</a><br/>"
//                    + Utilities.getLanguages("NewPassword") + ": " + randomPass;


            boolean bln = Utilities.sendMail(strEmail, Utilities.getLanguages("TieuDeEmailForgetPassword"),  "VN".equals(Utilities.getCurrentLanguage())?mailContent:mailContentEN);

            FacesContext.getCurrentInstance().getExternalContext().redirect("/forgetpasswordsuccess.html");

        } catch (Exception ex) {
            throw ex;
        }
    }

    public void DangNhap(ActionEvent event) throws SQLException {

        String Ma = String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("Ma"));
        String MatKhau = String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("MatKhau"));
        WEBParamCollection Params = new WEBParamCollection();
        Params.add(Ma);
        Params.add(MatKhau);

        List<Sys_nguoidung> lst = new ArrayList<>();
        try {
            lst = DAL.executeQuery("{call PG_Load_Sys_NguoiDung_Login(?,?)}", Command.sqlText, Params, Sys_nguoidung.class);
        } catch (SQLException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (lst == null || lst.size() <= 0) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", "<b style='color:red'>" + Utilities.getLanguages("TaiKhoanKhongHopLe") + "</b>");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("update=\"growl\"");
            return;
        }

        if ("".equals(lst.get(0).getMa().trim())) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", "<b style='color:red'>" + Utilities.getLanguages("TaiKhoanKhongHopLe") + "</b>");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("update=\"growl\"");
            return;
        }
        if (lst.get(0).getTrangThai() < 0) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", "<b style='color:red'>" + Utilities.getLanguages("TaiKhoanBiVoHieuHoa") + "</b>");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("update=\"growl\"");
            return;
        }
        if (lst.get(0).getTrangThai() == 0) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", "<b style='color:red'>" + Utilities.getLanguages("TaiKhoanChuaActive") + "</b>");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("update=\"growl\"");
            return;
        }
        Sys_UserModel objUser = new Sys_UserModel();
        objUser.setUserID(lst.get(0).getMa());
        objUser.setUserName(lst.get(0).getHo().trim() + " " + lst.get(0).getTen().trim());
        objUser.setNhomID(lst.get(0).getNhomID());
        objUser.setHo(lst.get(0).getHo());
        objUser.setTen(lst.get(0).getTen());
        objUser.setEmail(lst.get(0).getEmail());
        objUser.setDienThoai(lst.get(0).getDienThoai());
        objUser.setLoaiXeBan(lst.get(0).getLoaiXeBan());
        objUser.setLoai(lst.get(0).getLoai());

        FacesContext context = FacesContext.getCurrentInstance();

        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        HttpSession httpSession = request.getSession(false);
        httpSession.setAttribute(Utilities.getSS_USER(), objUser);
        try {
            if ("ADMINISTRATORS".equals(objUser.getNhomID())) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("/Admin/index.html");
            } else {
                
                if(blnIsSellClick)
                {
                    C_DangTinController dangtin= Utilities.getManagedBean(C_DangTinController.class);
                     if("2".equals(dangtin.getItem().getTuKhoaTimKiem()))
                        FacesContext.getCurrentInstance().getExternalContext().redirect("/Users/c/1/motobike.html");///Users/c/1/ad.html
                    else
                        FacesContext.getCurrentInstance().getExternalContext().redirect("/Users/c/1/ad.html");///Users/c/1/ad.html
                    //FacesContext.getCurrentInstance().getExternalContext().redirect("/pricing-and-packages.html");
                    
                }
                else
                    FacesContext.getCurrentInstance().getExternalContext().redirect("/index.html");
            }
            blnIsSellClick=false;
        } catch (IOException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void loginOpenId(Sys_nguoidung nd) {
        Sys_UserModel objUser = new Sys_UserModel();
        objUser.setUserID(nd.getMa());
        objUser.setUserName(nd.getHo().trim() + " " + nd.getTen().trim());
        objUser.setNhomID(nd.getNhomID());
        objUser.setHo(nd.getHo());
        objUser.setTen(nd.getTen());
        objUser.setEmail(nd.getEmail());
        objUser.setDienThoai(nd.getDienThoai());
        objUser.setLoaiXeBan(nd.getLoaiXeBan());
        objUser.setLoai(nd.getLoai());
        
        FacesContext context = FacesContext.getCurrentInstance();

        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        HttpSession httpSession = request.getSession(false);
        httpSession.setAttribute(Utilities.getSS_USER(), objUser);
        try {
            if ("ADMINISTRATORS".equals(objUser.getNhomID())) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("/Admin/index.html");
            } else {
                FacesContext.getCurrentInstance().getExternalContext().redirect("/index.html");
            }
        } catch (IOException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void onPageLoad_DangXuat() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        HttpSession httpSession = request.getSession(false);
        httpSession.removeAttribute(Utilities.getSS_USER());
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("/index.html");
        } catch (IOException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void onPageLoad_CheckAdmin() {
        if (!"ADMINISTRATORS".equals(findNhomID().trim().toUpperCase())) {
            onPageLoad_DangXuat();
        }
    }

    public void onPageLoad_CheckUsers() {
        if (!"USERS".equals(findNhomID().trim().toUpperCase())) {
            onPageLoad_DangXuat();
        }
    }

    public void onPageLoad_CheckSell() throws IOException {
        FacesContext.getCurrentInstance().getExternalContext().redirect("/pricing-and-packages.html");
        if (!"USERS".equals(findNhomID().trim().toUpperCase())) {
            blnIsSellClick=true;
           
            
        }
        
    }
    public void onPageLoad_Active() {
        WEBParamCollection Params = new WEBParamCollection();
        Params.add(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("usrid").toString());
        DAL.executeUpdate("{call Proc_Sys_NguoiDung_Active(?)}", Command.sqlStoredProcedure, Params);

    }

    public void onPageLoad_ChangeLanguage() throws SQLException, IOException {
        Utilities.setCurrentLanguage(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id").toString());
        Utilities.setLanguageData();
        FacesContext.getCurrentInstance().getExternalContext().redirect(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("url").toString());
        
    }

    public String findUserName() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj.getUserName();
        }
        return "";
    }

    public String findUserID() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj.getUserID();
        }
        return "";
    }

    public String findFirstName() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj.getHo();
        }
        return "";
    }

    public String findLastName() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj.getTen();
        }
        return "";
    }

    public String findPhone() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj.getDienThoai();
        }
        return "";
    }

    public String findEmail() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj.getEmail();
        }
        return "";
    }

    public static Sys_UserModel findUser() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj;
        }
        return new Sys_UserModel();
    }
    public Sys_UserModel findObjUser() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj;
        }
        return new Sys_UserModel();
    }
    public String findNhomID() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj.getNhomID();
        }
        return "";
    }

    public int findLoai() {
        HttpServletRequest httprequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession = httprequest.getSession();
        Sys_UserModel obj = (Sys_UserModel) httpsession.getAttribute(Utilities.getSS_USER());
        if (obj != null) {
            return obj.getLoai();
        }
        return 0;
    }

    public Sys_nguoidung findUserOpenId(String email, String type) {
        try {
            String sql = "select * from sys_nguoidung where sys_nguoidung.Ma='%s' and sys_nguoidung.OpenIdType='%s'";
            List<Sys_nguoidung> lst = DAL.executeQuery(String.format(sql, email, type), Sys_nguoidung.class);
            if(lst!=null && !lst.isEmpty())
                return lst.get(0);
        } catch (SQLException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    
    public void onPageLoad_ThongTinCaNhan() throws SQLException {
        if (!"".equals(findUserID().trim())) {
            WEBParamCollection Params=WEBParamCollection.getInstance();
            Params.add(findUserID());
            
            List<Sys_nguoidung> lst= DAL.executeQuery("Select *from sys_nguoidung where sys_nguoidung.Ma=?",Command.sqlText,Params,Sys_nguoidung.class);
            if(lst.size()>0)
            {
                this.setItem(lst.get(0));
            }
        }
        else
        {
            onPageLoad_DangXuat();            
        }
    }
    
    
}
